<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>售后申请 - 售后管理系统</title>
    <style>
        /* 保持原有样式不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 24px;
        }

        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .form-card {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .form-title {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
            font-size: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }

        .file-upload {
            border: 2px dashed #e1e5e9;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: border-color 0.3s ease;
        }

        .file-upload:hover {
            border-color: #667eea;
        }

        .file-upload input[type="file"] {
            display: none;
        }

        .upload-text {
            color: #666;
            font-size: 14px;
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s ease;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
        }

        .error-message {
            color: #e74c3c;
            font-size: 14px;
            margin-top: 10px;
            display: none;
        }

        .success-message {
            color: #27ae60;
            font-size: 14px;
            margin-top: 10px;
            display: none;
        }

        .loading {
            display: none;
            text-align: center;
            margin-top: 10px;
        }

        .spinner {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #667eea;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .order-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #e1e5e9;
            border-radius: 5px;
            margin-top: 10px;
        }

        .order-item {
            padding: 10px;
            border-bottom: 1px solid #e1e5e9;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .order-item:hover {
            background-color: #f8f9fa;
        }

        .order-item.selected {
            background-color: #667eea;
            color: white;
        }

        .existing-files {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }

        .existing-file-item {
            margin: 5px 0;
            padding: 5px;
            border-bottom: 1px solid #e1e5e9;
        }
    </style>
</head>
<body>
<div class="header">
    <h1 id="pageTitle">提交售后申请</h1>
    <a href="/after_sale_system/page/consumer/applicationList" class="back-btn">返回列表</a>
</div>

<div class="container">
    <div class="form-card">
        <h2 class="form-title" id="formTitle">售后申请表单</h2>

        <form id="applicationForm">
            <input type="hidden" id="applicationId">

            <div class="form-group">
                <label for="orderSelect">选择订单</label>
                <input type="text" id="orderSelect" placeholder="点击选择订单" readonly>
                <div class="order-list" id="orderList" style="display: none;">
                    <!-- 订单列表将通过JavaScript动态加载 -->
                </div>
            </div>

            <div class="form-group">
                <label for="afterSaleType">售后类型</label>
                <select id="afterSaleType" name="afterSaleType" required>
                    <option value="">请选择售后类型</option>
                    <option value="RETURN">退货</option>
                    <option value="EXCHANGE">换货</option>
                    <option value="REPAIR">维修</option>
                </select>
            </div>

            <div class="form-group">
                <label for="description">问题描述</label>
                <textarea id="description" name="description" placeholder="请详细描述您遇到的问题..." required></textarea>
            </div>

            <div class="form-group">
                <label>已上传凭证</label>
                <div id="existingFiles" class="existing-files" style="display: none;">
                    <!-- 现有文件将在这里显示 -->
                </div>
            </div>

            <div class="form-group">
                <label for="voucherFiles">上传新凭证（可选）</label>
                <div class="file-upload" onclick="document.getElementById('voucherFiles').click()">
                    <input type="file" id="voucherFiles" name="voucherFiles" multiple accept="image/*,.pdf">
                    <div class="upload-text">
                        <p>点击上传新凭证文件</p>
                        <p>支持图片和PDF格式，可多选</p>
                    </div>
                </div>
                <div id="newFileList"></div>
            </div>

            <button type="submit" class="submit-btn" id="submitBtn">提交申请</button>
        </form>

        <div class="error-message" id="errorMessage"></div>
        <div class="success-message" id="successMessage"></div>
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <span>处理中...</span>
        </div>
    </div>
</div>

<script>
    let selectedOrder = null;
    let uploadedFiles = [];
    let applicationId = null; // 用于存储当前编辑的申请ID

    // 页面加载时获取参数和数据
    window.addEventListener('load', function() {
        // 获取URL中的申请ID参数
        const params = new URLSearchParams(window.location.search);
        applicationId = params.get('applicationId');

        // 加载用户订单
        loadUserOrders();

        // 如果有申请ID，说明是编辑模式
        if (applicationId) {
            document.getElementById('pageTitle').textContent = '修改售后申请';
            document.getElementById('formTitle').textContent = '修改售后申请';
            document.getElementById('submitBtn').textContent = '保存修改';
            document.getElementById('applicationId').value = applicationId;

            // 加载申请详情
            loadApplicationDetail(applicationId);
        }
    });

    // 加载申请详情
    function loadApplicationDetail(id) {
        showLoading();
        fetch(`/after_sale_system/api/afterSale/detail/${id}`)
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    const application = data.data;
                    populateForm(application);
                } else {
                    showError('获取申请详情失败: ' + data.message);
                }
            })
            .catch(error => {
                hideLoading();
                console.error('获取申请详情失败:', error);
                showError('获取申请详情失败，请稍后重试');
            });
    }

    // 填充表单数据
    function populateForm(application) {
        // 订单信息（不可修改）
        selectedOrder = {
            id: application.orderId,
            orderNumber: application.orderNumber,
            productName: application.productName
        };
        document.getElementById('orderSelect').value = `${selectedOrder.orderNumber} - ${selectedOrder.productName}`;
        document.getElementById('orderSelect').readOnly = true;
        document.getElementById('orderList').style.display = 'none';

        // 售后类型
        document.getElementById('afterSaleType').value = application.afterSaleType;

        // 问题描述
        document.getElementById('description').value = application.applyReason;

        // 显示已上传的凭证
        const existingFilesContainer = document.getElementById('existingFiles');
        if (application.voucherUrls) {
            const fileUrls = application.voucherUrls.split(',');
            if (fileUrls.length > 0 && fileUrls[0] !== '') {
                existingFilesContainer.style.display = 'block';
                existingFilesContainer.innerHTML = '<p><strong>已上传文件：</strong></p>';

                fileUrls.forEach(url => {
                    const fileName = url.split('/').pop();
                    const fileItem = document.createElement('div');
                    fileItem.className = 'existing-file-item';
                    fileItem.innerHTML = `
                            <a href="${url}" target="_blank">${fileName}</a>
                        `;
                    existingFilesContainer.appendChild(fileItem);
                });
            }
        }
    }

    // 加载用户订单
    function loadUserOrders() {
        fetch('/after_sale_system/api/orders/getByUserId')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const orders = JSON.parse(data.data);
                    displayOrders(orders);
                } else {
                    showError('获取订单失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('获取订单失败:', error);
                showError('获取订单失败，请稍后重试');
            });
    }

    // 显示订单列表
    function displayOrders(orders) {
        const orderList = document.getElementById('orderList');
        const orderSelect = document.getElementById('orderSelect');

        orderList.innerHTML = '';

        orders.forEach(order => {
            const orderItem = document.createElement('div');
            orderItem.className = 'order-item';
            orderItem.innerHTML = `
                    <div><strong>订单号: ${order.orderNumber}</strong></div>
                    <div>商品: ${order.productName}</div>
                    <div>金额: ¥${order.amount}</div>
                `;
            orderItem.onclick = () => selectOrder(order);
            orderList.appendChild(orderItem);
        });

        // 点击输入框显示订单列表（仅在新建模式下）
        if (!applicationId) {
            orderSelect.onclick = () => {
                orderList.style.display = orderList.style.display === 'none' ? 'block' : 'none';
            };
        }
    }

    // 选择订单
    function selectOrder(order) {
        selectedOrder = order;
        document.getElementById('orderSelect').value = `${order.orderNumber} - ${order.productName}`;
        document.getElementById('orderList').style.display = 'none';
    }

    // 文件上传处理
    document.getElementById('voucherFiles').addEventListener('change', function(e) {
        const files = Array.from(e.target.files);
        uploadedFiles = files;
        displayFileList(files);
    });

    // 显示新上传的文件列表
    function displayFileList(files) {
        const fileList = document.getElementById('newFileList');
        fileList.innerHTML = '';

        files.forEach((file, index) => {
            const fileItem = document.createElement('div');
            fileItem.style.cssText = 'margin: 5px 0; padding: 5px; background: #f8f9fa; border-radius: 3px;';
            fileItem.innerHTML = `
                    <span>${file.name}</span>
                    <button type="button" onclick="removeFile(${index})" style="margin-left: 10px; color: red; border: none; background: none; cursor: pointer;">删除</button>
                `;
            fileList.appendChild(fileItem);
        });
    }

    // 删除文件
    function removeFile(index) {
        uploadedFiles.splice(index, 1);
        displayFileList(uploadedFiles);
    }

    // 表单提交
    document.getElementById('applicationForm').addEventListener('submit', function(e) {
        e.preventDefault();

        if (!selectedOrder) {
            showError('请选择订单');
            return;
        }

        const formData = new FormData();
        formData.append('orderId', selectedOrder.id);
        formData.append('productName', selectedOrder.productName);
        formData.append('afterSaleType', document.getElementById('afterSaleType').value);
        formData.append('description', document.getElementById('description').value);

        // 添加新文件
        uploadedFiles.forEach(file => {
            formData.append('voucherFiles', file);
        });

        showLoading();
        hideError();
        hideSuccess();

        let url = '/after_sale_system/api/afterSale/';
        let method = 'POST';

        // 如果是编辑模式，修改URL和方法
        if (applicationId) {
            url = `/after_sale_system/api/afterSale/update/${applicationId}`;
            method = 'PUT';
        }

        fetch(url, {
            method: method,
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                hideLoading();

                if (data.success) {
                    showSuccess(applicationId ? '申请修改成功！' : '申请提交成功！');
                    setTimeout(() => {
                        window.location.href = '/after_sale_system/page/consumer/applicationList';
                    }, 2000);
                } else {
                    showError(data.message || (applicationId ? '修改失败' : '提交失败'));
                }
            })
            .catch(error => {
                hideLoading();
                showError('网络错误，请稍后重试');
                console.error('操作失败:', error);
            });
    });

    // 工具方法
    function showError(message) {
        const errorElement = document.getElementById('errorMessage');
        errorElement.textContent = message;
        errorElement.style.display = 'block';
    }

    function hideError() {
        document.getElementById('errorMessage').style.display = 'none';
    }

    function showSuccess(message) {
        const successElement = document.getElementById('successMessage');
        successElement.textContent = message;
        successElement.style.display = 'block';
    }

    function hideSuccess() {
        document.getElementById('successMessage').style.display = 'none';
    }

    function showLoading() {
        document.getElementById('loading').style.display = 'block';
    }

    function hideLoading() {
        document.getElementById('loading').style.display = 'none';
    }
</script>
</body>
</html>